import { connect } from '../db'

// 获取服务器配置
export function getServerConfig() {
  const db = connect()
  const result = db.prepare('SELECT * FROM server_config WHERE id = 1').get()
  return result || {
    id: 1,
    base_url: 'http://192.168.0.151',
    base_url_with_port: 'http://192.168.0.151:2000',
    face2face: '8383',
    tts: '18180',
    kpop_baseUrl: 'http://192.168.0.151',
    created_at: Date.now(),
    updated_at: Date.now()
  }
}

// 获取服务器IP
export function getServerIP() {
  const db = connect()
  const result = db.prepare('SELECT * FROM server_config WHERE id = 1').get()
  return result || {
    id: 1,
    base_url: 'http://192.168.0.151',
    base_url_with_port: 'http://192.168.0.151:2000',
    kpop_baseUrl: 'http://192.168.0.151:2000',
    created_at: Date.now(),
    updated_at: Date.now()
  }
}

// 更新服务器配置
export function updateServerConfig(baseUrl,baseUrlWithPort, face2face, tts, kpop_baseUrl) {
  const db = connect()
  const now = Date.now()

  // 检查是否已有配置
  const existing = db.prepare('SELECT * FROM server_config WHERE id = 1').get()

  if (existing) {
    // 更新现有配置
    const info = db.prepare(
      'UPDATE server_config SET base_url = ?, base_url_with_port = ?, face2face = ?, tts = ?, kpop_baseUrl = ?, updated_at = ? WHERE id = 1'
    ).run(baseUrl, baseUrlWithPort, face2face, tts, kpop_baseUrl, now)
    return info
  } else {
    // 创建新配置
    const info = db.prepare(
      'INSERT INTO server_config (id, base_url, base_url_with_port, face2face, tts, kpop_baseUrl, created_at, updated_at) VALUES (1, ?, ?, ?, ?, ?, ?, ?)'
    ).run(baseUrl, baseUrlWithPort, face2face, tts, kpop_baseUrl, now, now)
    return info
  }
}
